'use strict';
const db = uniCloud.database()
const uniID = require('uni-id')
exports.main = async ({action,params,uniIdToken}, context) => {
	const collection = db.collection('recovery_order')
	const dbCmd = db.command
	const payload = await uniID.checkToken(uniIdToken)
	if (payload.code > 0) {
		return {
			code: 1001,
			msg: '用户身份验证失败，请重新登录'
		}
	}
	let {_id,state}=params
	let res =null;
	if(action=="add"){
		params.user_id=payload.uid
		res = await collection.add(params)
	}else if(action=="get"){
		res = await collection.where({user_id:payload.uid,state:dbCmd.in(state)}).get()
	}else if(action=="getAll"){
		res = await collection.where({state:dbCmd.in(state)}).get()
	}else if(action=="getReceivingOrders"){
		res = await collection.where({receivingOrdersUserId:payload.uid,state:dbCmd.in(state)}).get()
	}else if(action=="getById"){
		res = await collection.where({_id}).get()
		res=res.data[0]
	}else if(action=="upd"){
		delete params._id
		res = await collection.where({_id}).update(params)
	}else if(action=="getOrderLog"){
		console.log(payload.uid)
		res = await db.collection('order-log').where({user_id:payload.uid}).get()
	}else if(action=="getMyOrderLog"){
		res = await db.collection('order-log').where({user_id:payload.uid}).get()
	}else if(action=="del"){
		res = await collection.where({_id}).remove()
	}else if(action=="receivingOrders"){
		let data = await collection.where({_id}).get()
		if(data.data[0].state==0){
			let receivingOrdersUserInfo={};
			receivingOrdersUserInfo.avatarUrl=payload.userInfo.avatarUrl
			receivingOrdersUserInfo.mobile=payload.userInfo.authentication.mobile
			receivingOrdersUserInfo.nickName=payload.userInfo.authentication.nickName
			res=await collection.where({_id}).update({state:1,receivingOrdersUserInfo,receivingOrdersUserId:payload.uid})
		}
	}else if(action=="settlementOrder"){
		params.integral=Number(params.integral)
		await collection.where({_id}).update({//先修改订单
			state:4,
			weight:params.weight,
			integral:params.integral,
			checkImage:params.checkImage,
			settlementOrdersUserId:payload.uid,
			settlementOrdersDateTime:new Date().getTime()
		})
		let temp = await collection.where({_id}).get()
		temp=temp.data[0]
		
		const dbCmd = db.command
		await db.collection('uni-id-users').where({//修改账户余额
		  _id: payload.uid
		}).update({
			orderCount: dbCmd.inc(1),//结算订单总数
			payIntegral: dbCmd.inc(params.integral)//结算订单总金额
		})
		await db.collection('uni-id-users').where({//修改账户余额
		  _id: temp.user_id
		}).update({
			orderCount: dbCmd.inc(1),//结算订单总数
			integral: dbCmd.inc(params.integral)//结算订单总金额
		})
		await db.collection('order-log').add({//添加订单记录
			user_id:temp.user_id,
			order_id:params._id,
			integral:params.integral,
			weight:params.weight,
			payuser_id:payload.uid,
			garbageType:temp.garbageType,
			datetime:new Date().getTime()
		})
		res=temp
	}
	return res
};

